<?php

namespace App\Http\Services;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use \Exception;
use Illuminate\Support\Facades\Log;

class SMSServices
{

    public static function createClient()
    {
        $config = new Config([
            "accessKeyId" => 'LTAI5tDBzVPucVsuNbawDSHB',
            "accessKeySecret" => 'JMdiIfUuNHTsffthUs8QkXtT6vFIUX',
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    public static function sendSMS($phone, $params)
    {
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => "北京维晟达科技",
            'templateCode' => 'SMS_313071633',
            'templateParam' => $params,
        ]);
        try {
            $resp = $client->SendSms($sendSmsRequest);
            $res = json_decode(Utils::toJSONString($resp->body), true);
            Log::info('发送短信', ['phone' => $phone, 'params' => $params, 'res' => $res]);
            return $res ?? ['Code' => 'ERROR', 'Message' => '未知错误'];
            // array(
            //     'BizId' => '798811815340575803^0',
            //     'Code' => 'OK',
            //     'Message' => 'OK',
            //     'RequestId' => 'EA9EB97F-74A6-586D-8D4E-D5BAAB0406B3',
            // );
        } catch (Exception $error) {
            Log::info('发送短信', ['res' => $error]);
            return [
                'Code' => 'ERROR',
                'Message' => $error->getMessage(),
            ];
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }

            var_dump($error->message);
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }
}
